<template>
  <section>
    <slot></slot>
    <section
    class="detail-prescription-auxiliary"
    v-if="isAux"
    :class="[
    isDisabled ? 'disabled' : '',
    isFixedAux ? 'aux-fixed' : ''
    ]">
      <section class="aux-wrapper">
        <a class="aux-btn" @click="handleChangeAux">
          <i class="aux-control"></i>
          <span>辅助诊断</span>
        </a>
        <section id="cdss-clinic-prescription" class="aux-box" style="height: 100%; overflow-y: auto; overflow-x: hidden;">
        </section>
      </section>
    </section>
  </section>
</template>
<script>
import homeService from '@/services/home';
// import NpmCdss from '@weiyi/ai-cdss';
import { mapGetters } from 'vuex';
import { omit } from 'lodash';
import clinicService from '@/services/clinic';
import cookie from '@/utils/cookie';

const Cdss = window.Cdss;
export default {
  props: {
    isAux: {
      type: Boolean,
      default: false
    },
    toggleCdss: {
      type: Boolean,
      default: false
    },
    source: {
      type: [String, Number],
      default: ''
    },
    stores: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      cdss: null,
      pharmacyTypeMap: { // 云his的处方来源与cdss sdk中定义的来源关系表
        1: 1,
        6: 2
      },
      aiMedicalInfo: {}
    };
  },
  computed: {
    ...mapGetters({
      infoSum: 'clinic/infoSum',
      getAccount: 'auth/getAccount',
      patientItem: 'patient/patientItem'
    }),
    isDisabled () {
      if (this.infoSum && this.infoSum.clinicVisitStatus !== undefined) {
        return this.infoSum.clinicVisitStatus === 4;
      }
      return false;
    }
  },
  watch: {
    isAux (val) {
      if (val) {
        this.init();
      }
    }
  },
  methods: {
    // 修改辅助诊断
    handleChangeAux () {
      this.$emit('update:toggleCdss', !this.toggleCdss);
    },
    changeSource () { // 切换购买方式（来源）
      const params = {
        pharmacyType: this.pharmacyTypeMap[+this.source],
        supplierIdList: +this.source === 1 ? [] : this.stores
      };
      console.log(`cdss 组件开始更新药房`, params);
      this.cdss.changeDrugSource(params);
    },
    async setCdssInfo (stores) {
      if (!this.isAux) return;
      // 病历信息修改，给sdk传参
      // chiefComplaint: string, // 主诉, 可选, 默认: ''
      // nowMedicalHistory: string, // 现病史, 可选, 默认: ''
      // physicalExamination: string, // 体格检查, 可选, 默认: ''
      // generalInfo: string, // 辅助检查, 可选, 默认: ''
      // diagnosis: string, // 本次诊断, 可选, 默认: ''
      // suggestion: string, // 处理意见
      // this.$nextTick(async () =>
      // });
      let params = {};
      // 获取患者门诊信息
      this.aiMedicalInfo = await clinicService.apiGetAiMedicalInfo({
        visitId: this.$route.params.visitId,
        patientId: this.$route.params.patientId,
        hospId: this.getAccount.hospId,
        orgId: this.getAccount.orgId
      });
      Object.assign(params, this.aiMedicalInfo);
      // 诊断
      // selectTags，suspectItems
      // params.chiefComplaint = this.clinicForm.chiefComplain;
      let diagnoseStr = '';
      this.aiMedicalInfo.diagnosis.forEach((item, index) => {
        if (index === 0) {
          diagnoseStr = item.diseaseName;
        } else {
          diagnoseStr = diagnoseStr + ',' + item.diseaseName;
        }
      });
      params.diagnosis = diagnoseStr;
      // 过敏史
      let allergyHistoryStr = '';
      this.aiMedicalInfo.allergyHistory.forEach((item, index) => {
        if (index === 0) {
          allergyHistoryStr = item.allergenName;
        } else {
          allergyHistoryStr = allergyHistoryStr + ',' + item.allergenName + ',';
        }
      });
      allergyHistoryStr = allergyHistoryStr.replace(/,,/g, ',');
      if (allergyHistoryStr.charAt(allergyHistoryStr.length - 1) === ',') {
        allergyHistoryStr = allergyHistoryStr.substr(0, allergyHistoryStr.length - 1);
      }
      params.allergyHistory = allergyHistoryStr;
      params.bodyWeight = this.aiMedicalInfo.bodyWeight ? (this.aiMedicalInfo.bodyWeight / 1000 + 'kg') : '';
      params.bodyHeight = this.aiMedicalInfo.bodyHeight ? (this.aiMedicalInfo.bodyHeight / 10 + 'cm') : '';
      params.bmi = (this.aiMedicalInfo.bodyWeight && this.aiMedicalInfo.bodyHeight)
        ? ((this.aiMedicalInfo.bodyWeight / 1000) / ((this.aiMedicalInfo.bodyHeight / 10) * (this.aiMedicalInfo.bodyHeight / 10)) * 10000).toFixed(1) : '';
      params.sex = this.aiMedicalInfo.sex === 3 ? 3 : (this.aiMedicalInfo.sex === 1 ? 2 : 1);
      // 处理过敏史和诊断
      params.bizType = '1';
      params.insuranceNo = this.aiMedicalInfo.insuranceNo;
      params.doctorId = this.getAccount.userId;

      params.visitId = this.$route.params.visitId;
      params.name = params.patientName;
      params.age = this.infoSum.patientAge;
      params.pharmacyType = this.pharmacyTypeMap[+this.source];
      params.supplierIdList = +this.source === 1 ? [] : (stores || []);
      params.hospId = this.getAccount.hospId;
      params.deptId = this.infoSum.deptId;
      params.dep = this.infoSum.deptName;
      this.cdss.setPatient(params);
      return params;
    },
    getAge (str) {
      let year = 0;
      if (str) {
        const nowDate = new Date();
        const startDate = new Date(str);
        // 如果不是日期，返回传入值
        if (!startDate.getFullYear()) {
          return str;
        }
        let month = nowDate.getMonth() - startDate.getMonth();
        year = nowDate.getFullYear() - startDate.getFullYear();
        if (month < 0) {
          // const mValue = month;
          month = 12 + month;
          year += -1;
        }
      }
      return year;
    },
    async init () {
      const drugParams = await clinicService.apiGetCdssDrugParams(this.$route.params.visitId);

      const drugSearchParams = {
        ...omit(drugParams, 'appId'),
        weiyiAppid: drugParams.appId,
        weiyiAuthtoken: cookie.get('his_token')
      };
      try {
        this.cdss = new Cdss({
          id: '#cdss-clinic-prescription', // 挂载的元素, 可选 eg: #ai-cdss
          gatewayRoot: `${__globalEnv__.VUE_APP_AI_CDSS_GATEWAYROOT}`,
          drugSearchParams,
          apiRoot: `${__globalEnv__.VUE_APP_AI_CDSS_APIROOT}`, // 接口服务器地址 eg: 'http://192.168.94.44:11000'
          // apiRoot: 'http://cdss-chronic-web-qa2.guahao-test.com', // 接口服务器地址 eg: 'http://192.168.94.44:11000'
          // // dev: __globalEnv__.VUE_APP_CURRENTMODE === 'development' || __globalEnv__.VUE_APP_CURRENTMODE === 'test',
          // sdkTokenApi: window.location.origin + '/api/ai/token', // 获取token的接口(由第三方后台提供)接口格式见下, 必传 后端逻辑见CDSS鉴权认证机制文档
          // his_token: cookie.get('his_token', { domain: utils.getDomain() }),

          // dev: __globalEnv__.VUE_APP_CURRENTMODE === 'development' || __globalEnv__.VUE_APP_CURRENTMODE === 'test',
          sdkTokenRefresh: homeService.apiGetAccessToken,
          // 一键开处方的回调, 回传数据为开发数据，结构HIS定 TODO
          prescribingCallback: (_, prescriptionData) => {
          // 自动填充ai处方
          // this.setAiPrescription(prescriptionData);
            console.log('cdss 回调');
            this.$emit('setAiPrescription', prescriptionData);
          },
          feeNode: 1, // 控费节点来源：1-开方，2-收费
          hosTitle: '微医慢病决策支持系统',
          hospitalName: JSON.parse(sessionStorage.getItem('account')).hospitalName,
          orgCode: this.getAccount.orgId,
          prescriptionLIstCallback: async () => {
            const visitId = this.$route.params.visitId;
            const bizId = this.$route.query.bizId;
            const params = { visitId, pageSize: 500, pageNo: 1 };
            let res = {};
            if (this.source === 1) {
              res = await clinicService.apiGetSlowDrugCList({ params });
            } else {
            // 云药房
              res = await clinicService.apiGetCloudPharmacyDetail(bizId);
            }
            // console.log(res, '');
            const arr = [];
            res.list.forEach(item => {
              arr.push(item.drugName);
            });
            return arr;
          },

          // 检查是否有内容， 若有回调返回 true，否则 false
          detectDieaseCallback: (isSupport) => {
            if (isSupport) {
              this.$emit('update:isAux', true);
            }
          }
        });
      } catch (e) {
        console.log('cdss初始化失败');
      }
    }
  },
  async mounted () {
    // 初始化sdk
    if (this.isAux) {
      this.init();
    }
  },
  beforeDestroy () {
    this.cdss = null;
  }
};
</script>
<style lang="less">
.detail-prescription-auxiliary {
  position: absolute;
  top: 1px;
  right: -20px;
  transform: translateX(410px);
  transition: transform 0.3s ease-in-out;
  height: calc(~'100%');
  z-index: 8;

  .aux-wrapper {
    display: flex;
    height: 100%;

    .aux-btn {
      display: flex;
      align-items: center;
      justify-content: space-around;
      width: 34px;
      height: 80px;
      background-color: rgba(0, 0, 0, 0.5);
      color: white;
      border-radius: 3px;
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;
      font-size: 13px;
      line-height: 15px;
      cursor: pointer;
      margin-top: 0;
      padding: 0 3px;
      box-sizing: border-box;
      user-select: none;

      span {
        width: 13px;
      }

      i {
        display: block;
        width: 0;
        height: 0;
        border-width: 6px 0 6px 7px;
        border-style: solid;
        border-color: transparent transparent transparent @white;
        transition: transform 0.3s ease-in-out;
        transform: rotate(180deg);
      }
    }

    .aux-box {
      display: flex;
      flex-wrap: wrap;
      width: 414px;
      background-color: @white;
      box-shadow: -3px 0 5px rgba(0, 0, 0, 0.1);
      align-content: flex-start;

      .aux-search {
        width: 100%;
        padding: 15px 20px;
        height: 36px;

        i {
          cursor: pointer;

          &:hover {
            color: @blue6;
          }
        }
      }

      .aux-content {
        position: relative;
        width: 99%;
        height: calc(~'100% - 134px');
        overflow: hidden;

        /deep/ .el-scrollbar {
          height: 100%;
        }

        /deep/ .el-scrollbar__bar.is-vertical {
          right: 12px;
        }

        /deep/ .el-scrollbar__view {
          height: auto;
        }

        .aux-recommend {
          min-height: 400px;
        }

        .aux-search-content {
          min-height: 400px;
        }

        .list-title {
          padding: 0 20px;
          font-size: 13px;
          color: @gray5;
          letter-spacing: 0;
          line-height: 20px;
        }

        .aux-list {
          padding: 10px 0;

          .aux-item:first-child {
            .item-checkbox {
              border-top: 1px solid @blue15;
            }
          }
        }
      }
    }
  }
}
</style>
